/*
 * @Author: szx
 * @Date: 2022-03-06 13:00:53
 * @LastEditTime: 2022-03-06 14:56:30
 * @Description:
 * @FilePath: \leetcode\6000-6100\6017\6017.js
 */
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var minimalKSum = function (nums, k) {
    nums.sort((a, b) => a - b);
    nums.unshift(0);
    let res = 0;
    for (let i = 1; i < nums.length; i++) {
        const cnt = nums[i] - nums[i - 1] - 1;
        if (cnt <= 0) continue;
        const min = Math.min(cnt, k);
        res += Math.floor((min * (nums[i] + 1 + nums[i - 1] - 1)) / 2);
        k -= min;
        if (k == 0) return res;
    }
    let j = nums[nums.length - 1] + 1;
    res = BigInt(res) + BigInt(Math.floor((k * (j + j + k - 1)) / 2));
    return res;
};
console.log(minimalKSum([1, 4, 25, 10, 25], 2));
console.log(minimalKSum([5, 6], 6));
console.log(minimalKSum([1, 2, 3], 2));
console.log(minimalKSum([5, 6], 2));
console.log(minimalKSum([3, 5], 5));
console.log(minimalKSum([1], 1000000000));
console.log(minimalKSum([1000000000], 1000000000));
// console.log(minimalKSum([96, 44, 99, 25, 61, 84, 88, 18, 19, 33, 60, 86, 52, 19, 32, 47, 35, 50, 94, 17, 29, 98, 22, 21, 72, 100, 40, 84], 35));
